/**
 * 
 */
package Networking;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Jonas Spitzenpfeil
 * 
 */
public class Server implements Runnable {

	/** ServerSocket to listen for clients and support communication */
	private ServerSocket serverSocket = null;

	/** Only one socket because only one client allowed */
	private Socket clientSocket = null;

	/** Reader/Writer for the stream */
	private BufferedWriter writer = null;
	private BufferedReader reader = null;

	/** Receiver to get incoming messages */
	private ServerReceiver receiver = null;

	/**
	 * Constructor
	 * 
	 * @throws IOException
	 *             Is thrown if ServerSocket can not be created
	 */
	public Server(ServerReceiver recvr) throws IOException {
		serverSocket = new ServerSocket(8510);
		receiver = recvr;
	}

	/**
	 * @return The IP address of the ServerSocket
	 */
	public String getIPAddress() {
		return serverSocket.getInetAddress().getHostAddress();
	}

	/**
	 * @param line
	 *            The line that should
	 * @throws IOException
	 *             Is thrown if the line can not be written
	 */
	public void sendLine(String line) throws IOException {
		writer.write(line);
		writer.newLine();
		writer.flush();
	}

	public void kickClient() throws IOException {
		clientSocket.close();
		clientSocket = null;
	}

	@Override
	public void run() {
		String ip = "";

		while (true) {
			try {
				
				// Initialize Socket and Reader/Writer
				clientSocket = serverSocket.accept();
				
				// Initialize reader and writer
				writer = new BufferedWriter(new OutputStreamWriter(
						clientSocket.getOutputStream()));
				reader = new BufferedReader(new InputStreamReader(
						clientSocket.getInputStream()));

				// Get IP
				ip = clientSocket.getInetAddress().getHostAddress();
				receiver.clientConnected(ip);

				while (true) {
					// Call event that line received
					String line = reader.readLine();

					if (line != null) {
						receiver.lineReceived(line);
					} else {
						break;
					}
				}

				receiver.clientDisconnected(ip);
				clientSocket.close();

			} catch (Exception exc) {
				receiver.clientConnectionLost(ip, exc.getMessage());
			}
		}
	}

}
